#include "maindialog.h"
#include "ui_maindialog.h"

#include <QPushButton>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QMessageBox>
#include <QProcess>

#include <QDebug>

#include "components/numpad.h"

#include "definitions.h"
#include "settings.h"
#include "service.h"

#include "forms/loginform.h"
#include "forms/chequeform_mnk.h"
#include "forms/chequeform_touch.h"
#include "forms/moneymove.h"
#include "forms/updatehistory.h"
#include "forms/shellexecutor.h"
#include "forms/contactinfo.h"


MainDialog::MainDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    QVBoxLayout *lOpers = new QVBoxLayout();
    ui->wgOperations->setLayout(lOpers);
    lOpers->setSpacing(20);
    //layout->setContentsMargins(9,9,9,20);

    QHBoxLayout *lCurr = new QHBoxLayout();
    ui->wgCurrent->setLayout(lCurr);

    signalMapper = new QSignalMapper(this);

    QVBoxLayout *layout = (QVBoxLayout *) ui->wgOperations->layout();

    QPushButton *button;

    QSettings *settings = Settings::getInstance();

    int hgh = settings->value("globals/button_height").toInt();
    int size= settings->beginReadArray("operations");
    for(int i=0;i<size;++i){
        settings->setArrayIndex(i);

        button = new QPushButton(settings->value("operation").toString());
        button->setMinimumHeight(hgh);
        button->setFocusPolicy(Qt::NoFocus);

        connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
        QString sendStr = "operation:"+settings->value("operation").toString()+"|module:"+settings->value("module").toString()+"|params:"+settings->value("params").toString();

        signalMapper->setMapping(button, sendStr);
        if(firstElement.isEmpty())
            firstElement = sendStr;
        layout->addWidget(button);
    }
    settings->endArray();

    layout->addStretch(1);

    lbHistory = new QLabel(this);
    lbHistory->setText("");
    layout->addWidget(lbHistory);


    connect(signalMapper, SIGNAL(mapped(QString)),
            this, SLOT(operationSelected(QString)));

    if (!firstElement.isEmpty())
        operationSelected(firstElement);

    updateHeader();

    timerForClock   = startTimer(1000);
    //   timerForUpdate =  startTimer(30*60*1000);//startTimer(3*60*60*1000); //0.5 часа
    isFirstTimeTimer = true;

    this->installEventFilter(this);
}

MainDialog::~MainDialog()
{
    delete ui;
}


void MainDialog::operationSelected(const QString &buttontext){
    QHBoxLayout *layout = (QHBoxLayout *) ui->wgCurrent->layout();

    QStringList sl = buttontext.split("|");
    QString operation,module, params;

    foreach(const QString &s, sl){
        if(s.startsWith("operation:"))
            operation = s.mid(10);
        if(s.startsWith("module:"))
            module = s.mid(7);
        if(s.startsWith("params:"))
            params = s.mid(7);
    }

    QMap<QString,QVariant> *var = Settings::getVariables();

    FormInterface *fi = qobject_cast<FormInterface*>(current.data());
    if(fi)
        if(fi->isBusy()){
            QMessageBox *message = new QMessageBox(this);
            message->setText("Не закрыт текущий документ");
            message->exec();
            return;
        }


    if (module=="login"){
        if(current)
            current.clear();

        QWidget *wg = new LoginForm();
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);

        connect(wg, SIGNAL(loggedIn()), this, SLOT(selectCheque()));
    }


    if ((module=="cheque" || module=="cheque_touch") &&var->value("user").isValid()){
        if(current)
            current.clear();

        QWidget *wg = new ChequeForm_Touch(params);
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);

        if(params.contains("cheque for return")){
            connect(wg, SIGNAL(chequeCommited()), this, SLOT(selectCheque()));
        }
    }

    if ((module=="cheque_mnk") &&var->value("user").isValid()){
        if(current)
            current.clear();

        QWidget *wg = new ChequeForm_MnK(params);
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);

        if(params.contains("cheque for return")){
            connect(wg, SIGNAL(chequeCommited()), this, SLOT(selectCheque()));
        }
    }

    if (module=="moneymove"&&var->value("user").isValid()){
        if(current)
            current.clear();

        QWidget *wg = new MoneyMove(params);
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);
    }

    if (module=="updatehistory"&&var->value("user").isValid()){
        if(current)
            current.clear();

        QWidget *wg = new UpdateHistory();
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);
        updateHistory(0);
    }

    if (module=="shellexecutor"){
        if(current)
            current.clear();

        QWidget *wg = new ShellExecutor(params);
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);
    }

    if (module=="contacts"){
        if(current)
            current.clear();

        QWidget *wg = new ContactInfo();
        layout->addWidget(wg);
        wg->setFocus(Qt::OtherFocusReason);

        current = QSharedPointer<QWidget>(wg, &QObject::deleteLater);
    }

    if (var->value("user").isValid())
        var->insert("operation",operation);
    else
        var->insert("operation","");
    updateHeader();

}

void MainDialog::timerEvent(QTimerEvent *event)
{
    if(event->timerId()==timerForClock)
        ui->lbTime->setText(QDateTime::currentDateTime().toString("dd.MM.yy hh:mm"));

    /*
    if(event->timerId()==timerForUpdate || isFirstTimeTimer){
        isFirstTimeTimer = false;

        QProcess::startDetached(QString("")+"export LD_LIBRARY_PATH=./libs:/../libs:$LD_LIBRARY_PATH; qdbsync _syncs/sync.xml"+" last_update=\"'"+Settings::getPOSDefinition("last_update")+"'\" last_upload=\"'"+Settings::getPOSDefinition("last_upload")+"'\" this_base="+Settings::getDefinition("ТЕКУЩАЯ_БАЗА"));

//        qDebug()<<"start";
//        SqlSync *ssThread = new SqlSync("sync.xml",this);
//        connect(ssThread, &SqlSync::finished, ssThread, &QObject::deleteLater);
//        connect(ssThread, &SqlSync::isInserted, this, &MainDialog::updateHistory);//
//        ssThread->start();
    }
 */
}


void MainDialog::updateHeader()
{
    QMap<QString,QVariant> *var = Settings::getVariables();
    ui->lbUser->setText(var->value("user","").toString());
    ui->lbOperations->setText(var->value("operation","").toString());
}


void MainDialog::selectCheque(){
    //   current.clear();
    operationSelected(Settings::getInstance()->value("operations_defaults/operation_string").toString());
}


void MainDialog::updateHistory(int numRecords){
    if (numRecords > 0)
        lbHistory->setText("!!!!!!");
    else
        lbHistory->setText("");
}


bool MainDialog::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

        if(keyEvent->key()==Qt::Key_Escape){

            if (!firstElement.isEmpty())
                operationSelected(firstElement);

            return true;
        }
    }

    return QWidget::eventFilter(obj, event);
}
